package com.example.controller;

import com.example.entity.Article;
import com.example.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ArticleController {
    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping("/getArticles")
    @ResponseBody
    public List<Article> getArticles() {
        return articleMapper.selectList(null);
    }


    @GetMapping("/getArticle/{id}")
    @ResponseBody
    public Article getArticleById(@PathVariable Integer id) {
        // 增加预览量
        articleMapper.incrementViews(id);
        // 返回更新后的文章信息
        return articleMapper.selectById(id);
    }

    @PostMapping("/addArticle")
    @ResponseBody
    public String addArticle(@RequestBody Article article) {
        try {
            articleMapper.insert(article);
            return "文章添加成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "文章添加失败: " + e.getMessage();
        }
    }

    @GetMapping("/getArticlesByUserId/{userId}")
    @ResponseBody
    public List<Article> getArticlesByUserId(@PathVariable String userId) {
        return articleMapper.selectByUserId(userId);
    }

    @DeleteMapping("/deleteArticle/{id}")
    @ResponseBody
    public String deleteArticleById(@PathVariable Integer id) {
        try {
            int result = articleMapper.deleteById(id);
            if (result>0) {
                return "文章删除成功";
            } else {
                return "文章删除失败: 文章不存在";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "文章删除失败: " + e.getMessage();
        }
    }
}
